package org.openapi.vo;

import lombok.Data;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Excel数据格式
 */
@Data
public class TableExcel extends TableData{
    private List<ExcelField> fieldList;
    private String table;

    /**
     * 映射数据
     */
    private  Map<String,Object> dict = new HashMap<>();

    /**
     * 模型数据
     */
    private Map<String,List<ExcelField>> tableMap = new HashMap<>();

    /**
     * 数据类型
     */
    private Map<String,String> dataType = new HashMap<>();

    /**
     * 导入导出配置
     * "@excel":{
     *    "dept_id":"export"//只导出
     *    "age":"import"//只导入
     * }
     */
    protected Map excel = new HashMap();

    public void addDict(String key,String val){
        dict.put(key, val);
    }

    public Object getDict(String key){
        return dict.get(key);
    }

    public void addTable(String table, List<ExcelField> fields){
        tableMap.put(table, fields);
        if(this.table == null){
            this.table = table;
        }
    }

    public void setType(String field,String type){
        dataType.put(field, type);
    }
    public String getType(String field){
        return dataType.get(field);
    }

    /**
     * 生成导入导出的字段映射，中文名=》字段
     * @param imports 导入true 导出false
     * @return
     */
    public Map<String,String> getFieldMap(boolean imports){
        Map<String,String> fieldMap = new LinkedHashMap<>();
        List<ExcelField> fieldList = new ArrayList<>();
        for(String table:tableMap.keySet()){
            fieldList.addAll(tableMap.get(table));
        }
        fieldList.stream().sorted((a,b)->a.getIndex()-b.getIndex()).forEach(f->{
            if(imports && (!excel.containsKey(f.getDataField()) || "import".equalsIgnoreCase(excel.get(f.getDataField()).toString()))){
                fieldMap.put(f.getDataLabel().trim(), f.getDataField().trim());
            }else if(!imports && (!excel.containsKey(f.getDataField()) || "export".equalsIgnoreCase(excel.get(f.getDataField()).toString()))){
                fieldMap.put(f.getDataLabel().trim(), f.getDataField().trim());
            }
        });
        return fieldMap;
    }
}
